// 分类模块
import { topCategory } from '@/api/constants'
import { findAllCategoryAPI } from '@/api/category'

export default {
  namespaced: true,
  state () {
    return {
      // 分类信息集合
      list: topCategory.map(item => ({ name: item }))
    }
  },

  // 修改分类函数
  mutations: {
    // payload 所有的分类集合
    SET_CATEGORY (state, payload) {
      state.list = payload
    },
    // 定义show和hidden控制二级分类的显示与隐藏
    SHOW (state, id) {
      const currentCategory = state.list.find(item => item.id === id)
      currentCategory.open = true
    },
    HIDDEN (state, id) {
      const currentCategory = state.list.find(item => item.id === id)
      currentCategory.open = false
    }
  },

  // 获取分类函数
  actions: {
    async getList (context) {
      const data = await findAllCategoryAPI()
      // 给每个一级分类加上控制二级分类显示隐藏的数据
      data.result.forEach(top => {
        top.open = false
      })
      context.commit('SET_CATEGORY', data.result)
    }
  }
}
